package edu.upe.poli.dsc.sd.mensagem;
import java.net.InetAddress;
import java.net.UnknownHostException;


public class MessageId {
	
	private static char PORT_SEPARATOR = ':';
	private static char SEQUENCE_SEPARATOR = '#';
	private InetAddress host;
	private int port;
	private int sequence;
	
	public MessageId(String host, int port, int sequence) {
		
		try {
			this.host = InetAddress.getByName(host);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		this.port = port;
		this.sequence = sequence;
	}
	
	public MessageId(String composedId) {
		
		composedId = composedId.trim();
		
		int portIndex = composedId.indexOf(MessageId.PORT_SEPARATOR);
		
		try {
			this.host = InetAddress.getByName(composedId.substring(0, portIndex));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		int seqIndex = composedId.substring(portIndex).indexOf(MessageId.SEQUENCE_SEPARATOR);
		
		this.port = Integer.parseInt(composedId.substring(portIndex + 1, portIndex + seqIndex));
		
		this.sequence = Integer.parseInt(composedId.substring(portIndex + seqIndex + 1));
	}
	
	public String getIdString(){
		return host.getHostAddress()+MessageId.PORT_SEPARATOR+port+MessageId.SEQUENCE_SEPARATOR+sequence;
	}
	
	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getSequence() {
		return sequence;
	}

	public void setSequence(int sequence) {
		this.sequence = sequence;
	}
	
	public InetAddress getHost() {
		return host;
	}

	public void setHost(InetAddress host) {
		this.host = host;
	}

	public Id getId(){
		return new Id(getHost().getHostAddress(), getPort());
	}
	
	public String toString() {
		return getHost().getHostAddress() + ":" + this.getPort() + "#" + getSequence();
	}
	
	public int hashCode() {
		return (getHost().getHostAddress().hashCode() + getPort()) * 10000 * getSequence();
	}
	
	public boolean equals(Object obj) {
		
		if(obj instanceof MessageId == false)
			return false;
		
		MessageId id = (MessageId) obj;
		
		return this.getHost().getHostAddress().equals(id.getHost().getHostAddress()) && this.getPort() == id.getPort() && this.getSequence() == id.getSequence();
	}
}
